<?php
declare (strict_types = 1);
// +----------------------------------------------------------------------
// | Dustink Sms
// +----------------------------------------------------------------------
// | Copyright (c) 2021~2021 https://www.dustink.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: 尘墨成 <dustink@sina.com>
// +----------------------------------------------------------------------
// | 创建于2021年10月20日 02:23
// +----------------------------------------------------------------------
// | 阿里云短信服务类
// +----------------------------------------------------------------------

namespace DustInk\Sms\Channel;

use AlibabaCloud\SDK\Dysmsapi\V20170525\Dysmsapi;
use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\SDK\Dysmsapi\V20170525\Models\SendSmsRequest;

class Aliyun
{
    static public function init(string $accessKeyId, string $accessKeySecret) {
        $config = new Config([
            "accessKeyId" => $accessKeyId,
            "accessKeySecret" => $accessKeySecret
        ]);
        $config->endpoint = "dysmsapi.aliyuncs.com";
        return new Dysmsapi($config);
    }

    static public function send(array $config, string $action, array $args)
    {
        $client = self::init($config['accessKeyId'], $config['accessKeySecret']);
        $conf = $config['actions'][$action];
        $sendSmsRequest = new SendSmsRequest([
            'PhoneNumbers' => $args[0],
            'SignName' => $config['sign_name'],
            'TemplateCode' => $conf['template_id'],
            'TemplateParam' => json_encode($args[1]),
        ]);
        $result = $client->sendSms($sendSmsRequest);
        if ($result['Code'] == "OK") {
            $data['code'] = 200;
            $data['message'] = '发送成功';
        } else {
            $data['code'] = $result['Code'];
            $data['message'] = '发送失败，' . $result['Message'];
        }
        return $data;
    }
}